/**
 * @file 考虑高阶组件包裹的方式
 * */
import React from 'react';
import PropTypes from 'prop-types';
import { Table } from 'antd';
import './index.less';

class ListCard extends React.Component {
  static propTypes = {
    icon: PropTypes.element,
    title: PropTypes.string,
    loader: PropTypes.func,
    columns: PropTypes.array,
    getOperations: PropTypes.func,
    updatedAt: PropTypes.number,
    countRender: PropTypes.func
  };
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      pageSize: 10,
      count: 0,
      list: [],
      loading: false
    };
  }
  componentDidMount() {
    this.getList();
  }
  componentDidUpdate(prevProps) {
    if (this.props.updatedAt !== prevProps.updatedAt) {
      this.getList();
    }
  }
  getList() {
    const { page, pageSize } = this.state;
    this.setState({ loading: true });
    this.props
      .loader({ page, pageSize }, this.state)
      .then(([count = 0, list = [], ...rest] = []) => {
        this.setState({ list, count, rest });
      })
      .finally(() => {
        this.setState({ loading: false });
      });
  }
  onTableChange = ({ current, pageSize }) => {
    this.setState({ page: current, pageSize }, this.getList);
  };

  resertTable = () => {
    this.setState({ page: 1, pageSize: 10 }, this.getList);
  };

  render() {
    const { list, count, page, pageSize, loading } = this.state;
    const { icon, title, columns, countRender } = this.props;
    const operations =
      this.props.getOperations &&
      this.props.getOperations({
        state: this.state,
        setState: state => this.setState(state, this.getList)
      });
    let titleElement = typeof title === 'function' ? title(this.state) : title;
    return (
      <div className="list-card">
        <div className="list-card-title">
          {icon}
          <span className="text">
            {titleElement}&nbsp;({countRender ? countRender(this.state) : count})
          </span>
          {operations}
        </div>
        <Table
          className="data-table"
          loading={loading}
          dataSource={list}
          pagination={{
            current: page,
            pageSize,
            // size: 'small',
            style: { height: 40 },
            total: count,
            showQuickJumper: false,
            showTotal: false
          }}
          bordered={false}
          columns={columns}
          onChange={this.onTableChange}
        />
      </div>
    );
  }
}

export default ListCard;
